package com.huluobo.hyj.hyjmodel.adapter

import android.app.AlertDialog
import android.content.Context
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.huluobo.hyj.hyjmodel.R
import com.huluobo.hyj.hyjmodel.data.ContactListItem
import com.huluobo.hyj.hyjmodel.ui.activity.ChatActivity
import com.huluobo.hyj.hyjmodel.widet.ContactListItemView
import com.hyphenate.chat.EMClient
import org.jetbrains.anko.runOnUiThread
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

class ContactListAdapter(
    private val context: Context,
    val contactListItems: MutableList<ContactListItem>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        Log.i("Tag","123")
        return ContactListItemViewholder(ContactListItemView(context))
    }

    override fun getItemCount(): Int = contactListItems.size


    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

        val contactListItemView = holder.itemView as ContactListItemView
        contactListItemView.bindView(contactListItems[position])//给自定义view


        //点击联系人好友跳转聊天页面
        val UserName = contactListItems[position].userName  //kotlin里是数组的形式
        contactListItemView.setOnClickListener {
            context.startActivity<ChatActivity>("username" to UserName)
        }





        //长按删除 点击事件
        contactListItemView.setOnLongClickListener {
            val  message = String .format(context.getString(R.string.delete_friend_message),UserName)
            //创建一个窗口
            AlertDialog.Builder(context).setTitle(R.string.delete_friend_title)
                .setMessage(message)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.confirm) {
                        _, _ -> deleteFriend(UserName)
                }.show() //显示窗口
            true
        }
    }

    private fun deleteFriend(userName: String) {
        EMClient.getInstance().contactManager()
            .aysncDeleteContact(userName,object :EMCallbackAdapter(){
                //删除成功
                override fun onSuccess() {
                    context.runOnUiThread {toast(R.string.delete_friend_success)}
                }
                //删除失败
                override fun onError(code: Int, error: String?) {
                    context.runOnUiThread {toast(error+"，，"+R.string.delete_friend_failed)}
                }
            })
    }


    class ContactListItemViewholder(itemView:View?):RecyclerView.ViewHolder(itemView!!){

    }

}